﻿using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

namespace UFrame
{
    public abstract class BaseUI : BaseMono
    {
        public bool InitValue { get; set; }

        public int uiType { get; set; }

        public bool isMask;

        public UILayer uiLayer = UILayer.Default;

        public void OnBaseInit()
        {
            if (isMask)
            {
                AddMask();
            }
        }

        /// <summary>
        /// 第一次打开UI的时候
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        public virtual bool OnInit(object arg)
        {
            return true;
        }

        /// <summary>
        /// 每次显示UI时候
        /// </summary>
        public virtual void OnRefreshUI(object arg)
        {
        }

        public virtual void OnCloseUI()
        {
        }

        public virtual void OnDestroyUI()
        {
            eventc.UnRegisterEvent();
        }

        public void DestroyUI()
        {
            UIMa.DestroyUI(uiType);
        }

        public void CloseUI()
        {
            UIMa.DisplyUI(uiType, false);
        }


        private void AddMask()
        {
            GameObject go = new GameObject();
            var rt = go.AddComponent<RectTransform>();
            rt.SetParent(transform);
            rt.localScale = Vector3.one;
            rt.anchorMin = Vector2.zero;
            rt.anchorMax = Vector2.one;
            rt.sizeDelta = Vector2.zero;
            rt.anchoredPosition = Vector2.zero;
            UnityEngine.UI.Image i = rt.gameObject.AddComponent<UnityEngine.UI.Image>();
            i.color = new Color32(0, 0, 0, 36);
            rt.SetAsFirstSibling();
        }

        public static void AddEventTrigger(GameObject go, EventTriggerType type, UnityAction<BaseEventData> eventAcion)
        {
            EventTrigger trigger = go.GetComponent<EventTrigger>();
            if (trigger == null)
            {
                trigger = go.AddComponent<EventTrigger>();
            }

            EventTrigger.Entry entry = new EventTrigger.Entry();
            entry.eventID = type;
            entry.callback.AddListener(eventAcion);
            trigger.triggers.Add(entry);
        }
    }
}